﻿using System;
using System.Windows;
using Ping.App;
using Ping.Core;

namespace Ping.Client
{
	public partial class MainPage
	{
		// Constructor
		public MainPage()
		{
			InitializeComponent();
			Loaded += PageLoaded;
			Unloaded += PageUnloaded;
		}

		private void PageLoaded(object sender, RoutedEventArgs e)
		{
			Trace.RequestFinished += TraceRequestFinished;
		}

		private void PageUnloaded(object sender, RoutedEventArgs e)
		{
			Trace.RequestFinished -= TraceRequestFinished;
		}

		private void TraceRequestFinished(Result result, Exception e)
		{
			StateService.State.DnsResult = null;

			if (result is DnsResult)
			{
				StateService.State.DnsResult = result;
				NavigationService.Navigate(new Uri("/Pages/DnsResultPage.xaml", UriKind.Relative));
			}
			else if (result == null)
			{
				MessageBox.Show("The application server didn't respond", "Error", MessageBoxButton.OK);
			}
			else if (e != null)
			{
				MessageBox.Show("There was an error while communicating with the application server");
			}
			else if (result is OperationResult)
			{
				var status = (OperationResult) result;
				MessageBox.Show(string.Format("The application server responded with: {0}", status.Status), "Error",
				                MessageBoxButton.OK);
			}
			else
			{
				MessageBox.Show("The application server's response could not be handled", "Error", MessageBoxButton.OK);
			}
		}
	}
}